#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json

from flask import request
from flask import Blueprint
from Ump import webutil
from base import BaseHandler
from Ump.jsonify import data2json
from Ump.common import exception
from Ump.message_handler import MessageHandler

message_handler = MessageHandler()


from Ump.common import log

LOG = log.get_logger(__name__)

class FusionstorPipe(BaseHandler):

    def __init__(self, request=None):
        self.request = request

    def post(self):
        form_input = request.form
        msg = form_input['msg']
        if not isinstance(msg, dict):
            msg = json.loads(msg)

        if len(msg.keys()) != 1:
            err = u'controller received an invalid message'
            LOG.error(err)
            raise exception.StorageBus(err)

        if msg.keys()[0] in ["Login", "QueryDB", "EventCreate", "UserCreateForce"]:
            return self._action_without_auth(msg)
        return self._action_with_auth(msg)

    @webutil.authenticated()
    def _action_with_auth(self, msg):
        print "received message: %s" % str(msg)
        return self.action(msg)

    def _action_without_auth(self, msg):
       # with session_scope() as _ss:
        return self.action(msg)

    def action(self, msg):
        body = msg.values()[0]
        body['reply'] = {}
        result = webutil.ui_return(message_handler.analyse_msg, msg)
        result = json.loads(result[0])
        records = result.get('records')
        reply = result.get('reply', {})

        body['reply'] = reply 
        body['records'] = records
        result = data2json(msg)
        return result

    def GET(self):
        return

class AgentCallback(BaseHandler):
    def post(self):
        taskuuid = request.headers.get('taskuuid')
        response = request.data

        LOG.info('Receive Callback with header [%s] and response [%s]' % (taskuuid, response))
        message_handler.instance_map.task.on_callback(taskuuid, response)
        return 'SUCC'

app = Blueprint('fusionstor_pipe', __name__, template_folder='templates')
app.add_url_rule('/fusionstor_pipe', view_func=FusionstorPipe.as_view('fusionstor'))
app.add_url_rule('/callback', view_func=AgentCallback.as_view('Callback'))

